package com.zhike.b2b.news.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.zhike.b2b.base.BaseService;
import com.zhike.b2b.model.NewsClassVo;
import com.zhike.b2b.model.NewsVo;
import com.zhike.b2b.news.INewsService;
import com.zhike.b2b.util.ClassUtil;

@Service
public class NewsService extends BaseService implements INewsService {
	
	/**
	 * 根据类别ID查询资讯类别
	 * @param classId
	 * @return
	 */
	public NewsClassVo getClassById(String classId)
	{
		String sql = "select class_name,class_id,list_rule,store_path from  news_class where class_id = ? ";
		return jt.queryForObject(sql,  new RowMapper<NewsClassVo>() {
			 public NewsClassVo mapRow(ResultSet rs, int rowNum)
				throws SQLException {
				 NewsClassVo ncv = new NewsClassVo();
				 ncv.setClassId(rs.getString("class_id"));
				 ncv.setClassName(rs.getString("class_name"));
				 ncv.setListRule(rs.getString("list_rule"));
				 ncv.setStorePath(rs.getString("store_path"));
				 return ncv;
			}}, classId);
	}
	/**
	  * 根据条件查询资讯列表
	  * @param classId
	  * @param limitStr
	  * @param orderCln
	  * @param commend
	  * @return
	  */ 
	public List<NewsVo> queryNews(String classId,String limitStr,String orderCln)
	{
		List<NewsVo> lnc = jt.query(getSqlstr(classId,limitStr,orderCln,""),  new RowMapper<NewsVo>() {
			 public NewsVo mapRow(ResultSet rs, int rowNum)
				throws SQLException {
				 NewsVo ncv = new NewsVo();
				 ncv.setClassId(rs.getString("class_id"));
				 ncv.setNewsId(rs.getString("news_id"));
				 ncv.setListRule(rs.getString("list_rule"));
				 ncv.setStorePath(rs.getString("store_path"));
				 ncv.setHomeName(rs.getString("home_name"));
				 ncv.setArticleRule(rs.getString("article_rule"));
				 ncv.setTitle(rs.getString("title"));
				 
				 ncv.setUrl(ClassUtil.getObjUrl(ncv, ncv.getNewsId()));
				 return ncv;
			}});
		return lnc;
	}
	
	 
	 private String getSqlstr(String classId,String limitStr, String orderCln, String commend)
	  {
	    StringBuffer sb = new StringBuffer("select n.news_id,nc.store_path,nc.home_name,nc.article_rule,nc.list_rule,n.class_id,n.title ");
	    
	    sb.append(" from news n inner join news_class nc on n.class_id=nc.class_id where 1=1  ");
	    if (!classId.equals(""))
	      sb.append(" and n.class_id like '%" + classId + "%'");
	    if (!commend.equals(""))
	      sb.append(" and n.commend=" + commend);
	    sb.append(" and n.info_state=1 and n.remove_tag =1  ");
	    if (!orderCln.equals(""))
	      sb.append("  order by n." + orderCln + " desc ");
	    if (!limitStr.equals(""))
	      sb.append(" limit " + limitStr);
	    logger.debug("当前查询的语句为：" + sb.toString());
	    return sb.toString();
	  }
     
	 
}
